package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 联想词
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult findAssociate(UserSearchDto userSearchDto) {
        //1. 校验参数
        if(null == userSearchDto || StringUtils.isEmpty(userSearchDto.getSearchWords())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //2. 校验并修正显示的数据
        int size = userSearchDto.getPageSize();
        if(size > 20){
            size = 20;
        }

        //3. 查询数据
        Query query = Query
                .query(Criteria.where("associateWords").regex("^.*"+userSearchDto.getSearchWords()+".*$"))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size);
        List<ApAssociateWords> list = mongoTemplate.find(query, ApAssociateWords.class);

        //4. 封装并返回结果
        return ResponseResult.okResult(list);
    }
}
